import { PDFDocument } from 'pdf-lib'
import fs from 'fs'
import path from 'path'
import { nanoid } from 'nanoid'

// 支持的文件类型
const SUPPORTED_FILE_TYPES = {
  'application/pdf': '.pdf',
  'application/msword': '.doc',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
  'application/vnd.ms-excel': '.xls',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
  'application/vnd.ms-powerpoint': '.ppt',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation': '.pptx',
  'text/plain': '.txt',
  'text/rtf': '.rtf',
  'application/rtf': '.rtf',
  'image/jpeg': '.jpg',
  'image/png': '.png',
  'image/gif': '.gif',
  'image/bmp': '.bmp',
  'image/tiff': '.tiff'
}

// 验证文件类型
export const validateFileType = (mimetype) => {
  return SUPPORTED_FILE_TYPES.hasOwnProperty(mimetype)
}

// 文件名校验函数
export const validateFileName = (fileName) => {
  // 移除文件扩展名，只校验文件名部分
  const nameWithoutExt = fileName.replace(/\.[^/.]+$/, '')
  
  // order格式：前四位大写字母 + 中间10位数字 + 后两位大写字母
  const orderPattern = /^[A-Z]{4}\d{10}[A-Z]{2}$/
  
  // enquiry格式：前四位大写字母 + 中间10位数字 + 最后一位大写E
  const enquiryPattern = /^[A-Z]{4}\d{10}E$/
  
  const isOrderFormat = orderPattern.test(nameWithoutExt)
  const isEnquiryFormat = enquiryPattern.test(nameWithoutExt)
  
  return {
    isValid: isOrderFormat || isEnquiryFormat,
    format: isOrderFormat ? 'order' : (isEnquiryFormat ? 'enquiry' : null),
    fileName: nameWithoutExt
  }
}

// 获取文件扩展名
export const getFileExtension = (mimetype) => {
  return SUPPORTED_FILE_TYPES[mimetype] || ''
}

// 创建上传目录
export const ensureUploadDir = (dirPath) => {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true })
  }
}

// 生成唯一文件名
export const generateUniqueFileName = (originalName) => {
  const ext = path.extname(originalName)
  const baseName = path.basename(originalName, ext)
  const uniqueId = nanoid(8)
  return `${baseName}_${uniqueId}${ext}`
}

// 转换文件为PDF（使用新的转换工具）
export const convertToPdf = async (filePath, mimetype) => {
  try {
    console.log(`开始转换文件: ${filePath}, MIME类型: ${mimetype}`)
    
    const { convertFileToPdf } = await import('../utils/file-converter.js')
    const outputDir = path.dirname(filePath)
    
    const result = await convertFileToPdf(filePath, outputDir, mimetype)
    console.log(`文件转换成功: ${result}`)
    
    return result
  } catch (error) {
    console.error(`文件转换失败: ${filePath}`, error)
    throw new Error(`文件转换失败: ${error.message}`)
  }
}

// 提取PDF指定页数
export const extractFirstPages = async (pdfPath, pageCount = 1) => {
  try {
    const pdfBytes = fs.readFileSync(pdfPath)
    const pdfDoc = await PDFDocument.load(pdfBytes)
    
    const totalPages = pdfDoc.getPageCount()
    if (totalPages <= pageCount) {
      return pdfPath
    }
    // 删除末尾页数：确保删除不超过总页数
    const pagesToDelete = Math.min(pageCount, totalPages)
    const pagesToKeep = Math.max(totalPages - pagesToDelete, 0)
    
    // 创建新的PDF文档
    const newPdfDoc = await PDFDocument.create()
    
    // 复制保留的前置页（删除末尾N页后剩余的页）
    for (let i = 0; i < pagesToKeep; i++) {
      const [copiedPage] = await newPdfDoc.copyPages(pdfDoc, [i])
      newPdfDoc.addPage(copiedPage)
    }
    
    // 生成新的PDF字节数组
    const newPdfBytes = await newPdfDoc.save()
    
    // 生成新文件路径
    const dir = path.dirname(pdfPath)
    const baseName = path.basename(pdfPath, '.pdf')
    const suffix = pagesToDelete === 1 ? 'removeLast1page' : `removeLast${pagesToDelete}pages`
    const newPdfPath = path.join(dir, `${baseName}_${suffix}.pdf`)
    
    // 保存新PDF文件
    fs.writeFileSync(newPdfPath, newPdfBytes)
    
    return newPdfPath
  } catch (error) {
    throw new Error(`PDF处理失败: ${error.message}`)
  }
}

// 保持向后兼容性的函数
export const extractFirstThreePages = async (pdfPath) => {
  return extractFirstPages(pdfPath, 3)
}

// 清理临时文件
export const cleanupTempFiles = (filePaths) => {
  console.log(`开始清理 ${filePaths.length} 个临时文件`)
  filePaths.forEach(filePath => {
    if (fs.existsSync(filePath)) {
      try {
        fs.unlinkSync(filePath)
        console.log(`成功清理临时文件: ${filePath}`)
      } catch (error) {
        console.error(`清理文件失败: ${filePath}`, error)
      }
    } else {
      console.log(`临时文件不存在，跳过清理: ${filePath}`)
    }
  })
}